package org.example.os.synchronous.producer_comsumer;

import java.util.LinkedList;
import java.util.concurrent.Semaphore;

/**
 * 信号量
 */
public class SemaphoreAchievement {
    private final LinkedList<Integer> buffer = new LinkedList<>();
    private final Semaphore producerSemaphore;
    private final Semaphore consumerSemaphore;
    private final Semaphore mutex;

    public SemaphoreAchievement(int capacity){
        this.producerSemaphore = new Semaphore(capacity);
        this.consumerSemaphore = new Semaphore(0);
        this.mutex = new Semaphore(1);
    }

    public void produce() throws InterruptedException {
        int value = 0;
        while (true) {
            producerSemaphore.acquire();
            mutex.acquire();
            System.out.println("生产者生产: " + value);
            buffer.add(value++);
            mutex.release();
            consumerSemaphore.release();
            Thread.sleep(1000);
        }
    }

    public void consume() throws InterruptedException {
        while (true) {
            consumerSemaphore.acquire();
            mutex.acquire();
            int value = buffer.removeFirst();
            System.out.println("消费者消费: " + value);
            mutex.release();
            producerSemaphore.release();
            Thread.sleep(1000);
        }
    }
}

